﻿using Consul;


namespace IdentityServer.Extensions
{
    public static class ConsulHelper
    {
        // 服务注册
        public static void ConsulRegist(this IConfiguration configuration)
        {
            var ip = Environment.GetEnvironmentVariable("RUN_HOST_IP");
            if (string.IsNullOrEmpty(ip))
            {
                ip = string.IsNullOrWhiteSpace(configuration["ip"]) ? configuration["ServiceRegistry:Ip"] : configuration["ip"];
            }
            var hostPort = Environment.GetEnvironmentVariable("RUN_HOST_PORT");
            var port = string.IsNullOrEmpty(hostPort) ? int.Parse(configuration["ServiceRegistry:Port"]) : int.Parse(hostPort);

            var regPort = configuration["ServiceRegistry:RegPort"];
            var regip = string.IsNullOrWhiteSpace(configuration["regip"]) ? ip : configuration["regip"];
            int weight = string.IsNullOrWhiteSpace(configuration["weight"]) ? 1 : int.Parse(configuration["weight"]);
            var groupName = configuration["ServiceRegistry:GroupName"];

            var client = new ConsulClient(c =>
            {
                c.Address = new Uri($"http://{regip}:{regPort}");
                c.Datacenter = "dc1"; //数据中心
            });
            
            client.Agent.ServiceRegister(new AgentServiceRegistration()
            {
                ID = $"service{ip}:{port}",//唯一的,端口只能启动一次
                Name = groupName,//组名称
                Address = ip,//其实应该写ip地址
                Port = port,//不同实例
                Tags = new string[] { weight.ToString() },//标签
                Check = new AgentServiceCheck()//配置健康检查
                {
                    Interval = TimeSpan.FromSeconds(15),
                    HTTP = $"http://{ip}:{port}/api/Health/Index",
                    Timeout = TimeSpan.FromSeconds(5),
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5)
                }
            });
            Console.WriteLine($"Application run at http://{ip}:{port}");
        }
    }
}
